﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using QD.WX.BLL;

namespace DaZhong.app_code
{
    /// <summary>
    /// 通过文章标题查找对于文章是否是原创
    /// </summary>
    public static class WxCopyRightValidate
    {
        private const string SearchUrl = "http://weixin.sogou.com/weixin?type=2&query={0}&ie=utf8";
        /// <summary>
        /// 文章标题
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public static async Task<bool> ValidateCopyRight(string title)
        {
            try
            {
                if (string.IsNullOrEmpty(title)) return false;
                var searchResult =await SearchKeyWord(title);
                var articles = GetArticles(searchResult);
                if (articles.Count == 0) return false;
                var art = articles[0];//第一篇为最准确的搜索结果
                var m1 = Regex.Matches(art.Title, "[\u4e00-\u9fa5]+").Cast<Capture>().Select(t => t.Value).Aggregate((a, b) => a + b);
                var m2 = Regex.Matches(title, "[\u4e00-\u9fa5]+").Cast<Capture>().Select(t => t.Value).Aggregate((a, b) => a + b);
                return m1.Equals(m2)&&await FindCopyRight(art.Url.ToString());
            }
            catch (Exception e)
            {
               Trace.WriteLine(e.Message);
            }
            return false;

        }
        /// <summary>
        /// 通过关键词搜索文章,只取第一页
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public static async Task<string> SearchKeyWord(string keyword)
        {
            if (string.IsNullOrEmpty(keyword)) return string.Empty;
            var requestUrl= string.Format(SearchUrl, HttpUtility.UrlEncode(keyword));
            return await SogouClient.Search(requestUrl);
        }

        /// <summary>
        /// 根据文章的Url搜索原创标签
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<bool> FindCopyRight(string url)
        {
            if (string.IsNullOrEmpty(url)) return false;
            var htmlResult =await SogouClient.Get(url);
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlResult);
            var spanLogo = doc.DocumentNode.SelectSingleNode("//*[@id=\"copyright_logo\"]");
            return spanLogo != null && spanLogo.InnerText.Trim().Equals("原创", StringComparison.OrdinalIgnoreCase);
        }

        public static IList<WcArticle> GetArticles(string htmlResult)
        {
            IList<WcArticle> list=new List<WcArticle>();
            var doc =new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlResult);
            var nodes = doc.DocumentNode.SelectNodes("//*[@class=\"news-list\"]/li");
            foreach (var node in nodes)
            {
                var title = node.SelectSingleNode("div/h3/a").InnerText;
                title = title.Replace("<!--red_beg-->", "");
                title = title.Replace("<!--red_end-->", "");
                var href =HttpUtility.HtmlDecode(node.SelectSingleNode("div/h3/a").Attributes["href"].Value);
                
                list.Add(new WcArticle() {Title = title,Url = href});
                
            }
            return list;
        }

    }

    public class WcArticle
    {
        public string Title { get; set; }
        public string Url { get; set; }
    }

    public  class SogouClient
    {
        public static CookieCollection SogouCookie {
            get
            {
                var col=new CookieCollection();
                var row = new JietuDAL.DateHelp().Select().Tables[0].Rows[0];
                col.Add(new Cookie("SNUID",row[0].ToString(),"/",".sogou.com"));
                col.Add(new Cookie("SUV",row[1].ToString(),"/",".sogou.com"));
                return col;
            }
        }

        public static async Task<string> Search(string url)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;
            WebRequestHelper.cookie=new CookieContainer();
            WebRequestHelper.cookie.Add(SogouCookie);
            WebRequestHelper.Host = "weixin.sogou.com";
            WebRequestHelper.Referer = url;
            return await WebRequestHelper.RequestAsync(url);
        }

        public static async  Task<string> Get(string url)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;
            WebRequestHelper.Clear();
            return await WebRequestHelper.RequestAsync(url);
        }
    }
}
